﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace FB.Annotations.Api
{
    public class SecurityKeyOnlyBaseAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected const string BasicAuthResponseHeader = "WWW-Authenticate";
        protected const string BasicAuthResponseHeaderValue = "Basic";

        public SecurityKeyOnlyBaseAttribute() { }

        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext == null)
                throw new ArgumentNullException("actionContext");

            //never authorize someone who isn't logged in
            var user = HttpContext.Current.User;
            if (!user.Identity.IsAuthenticated)
                this.HandleUnauthorizedRequest(actionContext);

            var keyObject = GetSecurityKey();

            if (null == keyObject || !keyObject.ValidateUser() || string.IsNullOrEmpty(keyObject.GetPassKey()))
                this.HandleUnauthorizedRequest(actionContext);
        }


        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext == null)
                throw new ArgumentNullException("actionContext");
            actionContext.Response = CreateUnauthorizedResponse(actionContext.ControllerContext.Request);

        }

        public virtual HttpResponseMessage CreateUnauthorizedResponse(HttpRequestMessage request)
        {
            var result = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.Unauthorized,
                RequestMessage = request
            };

            //we need to include WWW-Authenticate header in our response,
            //so our client knows we are using HTTP authentication
            //result.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
            return result;
        }



        public virtual FB.Data.Models.ISecurityKey GetSecurityKey()
        {
            throw new NotImplementedException();
        }

    }
}
